<template>
  <div class="page-common-layout drawing-manage-container">
    <!-- 查询条件 -->
    <div class="search-condition-warp">
      <div class="condition-warp">
        <!-- 项目 -->
        <a-tree-select
          style="width: 350px"
          v-model="condition.proCode"
          show-search
          placeholder="请选择项目"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          allow-clear
          tree-default-expand-all
          :loading="condition.treeLoading"
          treeNodeFilterProp="title"
          :replaceFields="{
            children: 'child',
            title: 'orgName',
            key: 'id',
            value: 'orgCode',
          }"
          :tree-data="condition.treeData"
          @change="tenantChange"
        >
        </a-tree-select>
        <!-- 文件名 -->
        <a-input
          allowClear
          placeholder="请输入文件名称"
          v-model="condition.fileName"
          style="width: 180px"
        >
        </a-input>
        <!-- 日期范围 -->
        <a-range-picker
          format="YYYY-MM-DD HH:mm:ss"
          valueFormat="YYYY-MM-DD HH:mm:ss"
          v-model="condition.date"
          :show-time="{
            hideDisabledOptions: true,
            defaultValue: [
              moment('00:00:00', 'HH:mm:ss'),
              moment('11:59:59', 'HH:mm:ss'),
            ],
          }"
        />
        <!-- 上传人 -->
        <a-input
          placeholder="请输入上传人"
          style="width: 180px"
          v-model="condition.creator"
        />
      </div>
      <div class="button-warp">
        <a-button type="primary" icon="search" @click="handleSearch()"
          >查询</a-button
        >
        <a-button icon="sync" @click="handleReset()">重置</a-button>
      </div>
    </div>
    <div class="result-body-warp">
      <!-- 图纸管理 -->
      <div class="drawing-container">
        <div class="header">
          图纸管理
          <icon-font
            type="icon-xinjianwenjianjia"
            class="add-file-button"
            @click="addFolder(0, '')"
          ></icon-font>
        </div>
        <div class="condition">
          <a-input placeholder="请输入关键字" v-model="keyWord" />
          <div class="search-btn">
            <a-icon type="search" @click="handleFilterTree()" />
          </div>
        </div>
        <div class="tree-container">
          <a-empty v-if="treeData.length == 0" :description="false" />
          <a-tree
            v-else
            v-model="checkedKeys"
            show-icon
            :expanded-keys="expandedKeys"
            :auto-expand-parent="autoExpandParent"
            :selected-keys="selectedKeys"
            :tree-data="treeData"
            :replaceFields="{
              children: 'children',
              title: 'nodeName',
              key: 'uuid',
            }"
            @expand="onExpand"
            @select="onSelect"
          >
            <!-- 自定义图标 -->
            <template slot="custom">
              <icon-font type="icon-wenjianjia-" />
            </template>
            <template slot="title" slot-scope="{ nodeName, id, uuid, unit }">
              <div class="custom-tree-title-warp">
                <div class="title">
                  {{ nodeName }}
                </div>
                <div class="operate">
                  <!-- 新增 -->
                  <icon-font
                    type="icon-xinjianwenjianjia"
                    class="add-file-button"
                    @click.stop="addFolder(id)"
                  ></icon-font>
                  <!-- 编辑 -->
                  <a-icon
                    type="edit"
                    class="edit-btn"
                    @click.stop="editFolder(nodeName, uuid, unit)"
                  />
                  <!-- 修改 -->
                  <a-icon
                    type="delete"
                    class="delete-btn"
                    @click.stop="deleteFolder(uuid)"
                  />
                </div>
              </div>
            </template>
          </a-tree>
        </div>
      </div>
      <!-- 列表 -->
      <div class="right-container">
        <div class="header">
          <a-button
            type="primary"
            :disabled="!condition.proCode"
            icon="cloud-upload"
            @click="uploadFolder()"
            >上传</a-button
          >
        </div>
        <div class="table-container">
          <!-- table -->
          <vxe-table
            ref="xTable"
            height="99%"
            align="center"
            show-overflow
            show-header-overflow
            border="inner"
            :data="tableData"
            :column-config="{ resizable: true }"
            size="small"
            :loading="tableLoading"
          >
            <vxe-column type="seq" width="80" title="序号"></vxe-column>
            <vxe-column title="文件名称" field="fileName" min-width="300">
            </vxe-column>
            <vxe-column field="commentName" title="文件查看/下载" width="160">
              <template #default="{ row }">
                <!-- 预览 -->
                <a-tooltip placement="top">
                  <template slot="title">
                    预览
                  </template>
                  <a-icon
                    type="eye"
                    class="preview-btn"
                    @click="previewFile(row)"
                  />
                </a-tooltip>
                <!-- 下载 -->
                <a-tooltip placement="top">
                  <template slot="title">
                    下载
                  </template>
                  <a-icon
                    type="download"
                    class="download-btn"
                    @click="downloadFile(row)"
                  />
                </a-tooltip>
              </template>
            </vxe-column>
            <vxe-column field="createTime" title="上传时间" width="200">
            </vxe-column>
            <vxe-column field="creator" title="上传人" width="140">
            </vxe-column>
            <!-- dataSetId -->
            <vxe-column field="correlation" title="关联模型" width="130">
              <template #default="{ row }">
                <div class="correlation-model" :class="!row.dataSetId && 'no'">
                  <icon-font
                    :type="row.dataSetId ? 'icon-wancheng' : 'icon-weiwancheng'"
                    class="location-button"
                  ></icon-font>
                  {{ row | relevanceText }}
                </div>
              </template>
            </vxe-column>
            <vxe-column field="operate" title="操作" fixed="right" width="130">
              <template #default="{ row }">
                <!-- 编辑 -->
                <a-tooltip placement="top">
                  <template slot="title">
                    编辑
                  </template>
                  <a-icon type="edit" class="edit-btn" @click="editFile(row)" />
                </a-tooltip>
                <!-- 删除 -->
                <a-tooltip placement="top">
                  <template slot="title">
                    删除
                  </template>
                  <a-icon
                    type="delete"
                    class="delete-btn"
                    @click="deleteFile(row.uuid)"
                  />
                </a-tooltip>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
        <!-- 分页 -->
        <div class="pager-container">
          <vxe-pager
            size="small"
            background
            :current-page.sync="pager.page"
            :page-size.sync="pager.pageSize"
            :total="pager.total"
            :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes']"
            :page-sizes="[20, 50, 100, 500]"
            @page-change="paginationChange"
          >
            <template #left>
              <div class="vxe-pager-left-tip-container">
                共<span>{{ pager.total }}</span
                >条
              </div>
            </template>
          </vxe-pager>
        </div>
      </div>
    </div>
    <!-- 新增、编辑弹窗 -->
    <addModal
      :visible.sync="addModal.visible"
      :operate="addModal.operate"
      :pid="addModal.pid"
      :nodeName="addModal.nodeName"
    ></addModal>
    <!-- 上传弹窗 -->
    <uploadModal
      :visible.sync="uploadModal.visible"
      :operate="uploadModal.operate"
    ></uploadModal>
  </div>
</template>
<script>
// 图纸管理
import moment from "moment";
import { Icon } from "ant-design-vue";
import iconfrontjs from "@/assets/IconFont/iconfont.js";
const iconFrontUrl = iconfrontjs;
const IconFont = Icon.createFromIconfontCN({
  scriptUrl: iconFrontUrl,
});
import { addAttributeByKey, flatTreeData } from "@/utils/util.js";
import cloneDeep from "lodash.clonedeep";
import { axios } from "@/utils/request";
import { getProListTreeByQX } from "@/api/common";
//新建弹窗
import addModal from "./addModal";
//上传弹窗
import uploadModal from "./uploadModal";
export default {
  data() {
    return {
      //查询体条件
      condition: {
        //项目名称
        proCode: undefined,
        treeData: [],
        treeLoading: false,
        //文件名称
        fileName: undefined,
        //日期范围
        date: [],
        //上传人
        creator: "",
      },
      //table
      tableData: [],
      tableLoading: false,
      pager: {
        page: 1,
        pageSize: 20,
        total: 0,
      },
      //图纸管理
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      treeData: [],
      cloneTreeData: [],
      currentTreeNode: {},
      keyWord: "",
      //新增编辑
      addModal: {
        visible: false,
        operate: 1,
        pid: "",
        nodeName: "",
        unit: undefined,
      },
      //上传
      uploadModal: {
        visible: false,
        operate: 1,
        row: {},
      },
    };
  },
  components: { IconFont, addModal, uploadModal },
  filters: {
    relevanceText(row) {
      let { dataSetId } = row;
      if (dataSetId) {
        return "已关联";
      } else {
        return "未关联";
      }
    },
  },
  mounted() {
    this.getProjectTreeData();
  },
  methods: {
    //查询按钮
    handleSearch() {
      let { id } = this.currentTreeNode;
      let { proCode, creator, fileName, date } = this.condition;
      if (!proCode || !id) {
        return;
      }
      this.tableLoading = true;
      let { page, pageSize } = this.pager;
      axios
        .post(
          `/probusiness/bimCadFile/getPageSet?pageNo=${page}&pageSize=${pageSize}`,
          {
            classifyId: id,
            proCode,
            fileName,
            creator,
            startTime: date?.[0] ?? "",
            endTime: date?.[1] ?? "",
          },
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          let { data } = res;
          this.tableData = data?.rows ?? [];
          this.pager.total = data?.totalCount ?? 0;
        })
        .catch((_) => {
          this.tableData = [];
          this.pager.total = 0;
          reject();
        })
        .finally((_) => {
          this.tableLoading = false;
        });
    },

    //重置
    handleReset() {
      let { treeData } = this.condition;
      this.condition = {
        //项目名称
        proCode: undefined,
        treeLoading: false,
        fileName: undefined,
        date: [],
        creator: "",
        treeData,
      };
      this.expandedKeys = [];
      this.autoExpandParent = true;
      this.checkedKeys = [];
      this.selectedKeys = [];
      this.treeData = [];
      this.cloneTreeData = [];
      this.tableData = [];
      this.currentTreeNode = {};
    },

    //查询项目列表-树形
    getProjectTreeData() {
      this.condition.treeLoading = true;
      return new Promise((resolve, reject) => {
        getProListTreeByQX()
          .then((res) => {
            let { data } = res;
            this.condition.treeData = data ?? [];
            resolve();
          })
          .catch((_) => {
            this.condition.treeData = [];
            reject();
          })
          .finally((_) => {
            this.condition.treeLoading = false;
          });
      });
    },

    //监听项目切换
    tenantChange(value) {
      this.condition.fileName = "";
      this.condition.date = [];
      this.condition.creator = "";
      this.tableData = [];
      this.expandedKeys = [];
      this.autoExpandParent = true;
      this.checkedKeys = [];
      this.selectedKeys = [];
      this.treeData = [];
      this.cloneTreeData = [];
      this.tableData = [];
      this.currentTreeNode = {};
      this.getDrawingTreeData();
    },

    //查询图纸树形数据
    getDrawingTreeData() {
      let { proCode } = this.condition;
      return new Promise((resolve, reject) => {
        axios
          .post(
            `/probusiness/bimCadClassify/getTreeByProCode?proCode=${proCode}`,
            {},
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            let { data } = res;
            this.cloneTreeData = cloneDeep(data ?? []);
            let flatData = flatTreeData(this.cloneTreeData, "children");
            this.expandedKeys = flatData.map((v) => v.uuid).filter((v) => v);
            let filterData = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              this.cloneTreeData,
              "children"
            );
            this.treeData = filterData ?? [];
            resolve();
          })
          .catch((_) => {
            this.expandedKeys = [];
            this.treeData = [];
            this.cloneTreeData = [];
            reject();
          })
          .finally((_) => {});
      });
    },

    //查询图纸管理树
    handleFilterTree() {
      let { keyWord, cloneTreeData } = this;
      let cloneData = cloneDeep(cloneTreeData);
      this.treeData = this.filterTree(cloneData, "children", (node) =>
        node.nodeName.includes(keyWord)
      );
    },

    //上传文件
    uploadFolder() {
      this.uploadModal.operate = 1;
      this.uploadModal.row = {};
      this.uploadModal.visible = true;
    },

    //新建文件夹
    addFolder(id) {
      let { proCode } = this.condition;
      if (!proCode) {
        this.$message.warning("请先选择项目");
        return;
      }
      this.addModal.pid = id;
      this.addModal.unit = undefined;
      this.addModal.nodeName = "";
      this.addModal.operate = 1;
      this.addModal.visible = true;
    },

    //编辑文件夹
    editFolder(nodeName, uuid, unit) {
      this.addModal.operate = 2;
      this.addModal.pid = uuid;
      this.addModal.unit = unit;
      this.addModal.nodeName = nodeName;
      this.addModal.visible = true;
    },

    //删除
    deleteFolder(uid = "") {
      let { uuid } = this.currentTreeNode;
      let that = this;
      that.$confirm({
        title: "提示",
        content: "确定删除该数据吗？删除之后不可恢复！",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          return new Promise((resolve, reject) => {
            that
              .$post(`/probusiness/bimCadClassify/deleteData?uuid=${uid}`)
              .then((res) => {
                let { statusCode, message } = res;
                if (statusCode == 200) {
                  that.$message.success("删除成功！");
                  if (uuid == uid) {
                    this.currentTreeNode = {};
                    this.tableData = [];
                  }
                  that.getDrawingTreeData();
                } else {
                  that.$message.error(message ?? "删除失败，请稍后重试！");
                }
                resolve();
              })
              .catch((_) => {})
              .finally((_) => {});
          }).catch(() => console.log("Oops errors!"));
        },
      });
    },

    //文件预览
    previewFile(row = {}) {
      let { uuid, fileInfo, unit } = row;
      let { fileName } = fileInfo;
      let domain = location.origin;
      window.open(
        `${domain}/#/blackHole/previewCad?uuid=${uuid}&fileName=${fileName}&unit=${unit}`
      );
    },

    //文件下载
    downloadFile(row = {}) {
      let { fileInfo } = row;
      let { url, fileName } = fileInfo;
      // 创建一个<a>元素
      const link = document.createElement("a");
      link.href = url; // 设置图片的URL
      link.download = fileName; // 设置下载后的文件名
      document.body.appendChild(link); // 将<a>元素添加到页面中
      link.click(); // 模拟点击<a>元素
      document.body.removeChild(link); // 移除<a>元素
    },

    //文件编辑
    editFile(row = {}) {
      this.uploadModal.operate = 2;
      this.uploadModal.row = row;
      this.uploadModal.visible = true;
    },

    //文件删除
    deleteFile(uuid = "") {
      let that = this;
      that.$confirm({
        title: "提示",
        content: "确定删除该数据吗？删除之后不可恢复！",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          return new Promise((resolve, reject) => {
            that
              .$post(`/probusiness/bimCadFile/deleteBatch?uuid=${uuid}`)
              .then((res) => {
                let { statusCode } = res;
                if (statusCode == 200) {
                  that.$message.success("删除成功！");
                  that.handleSearch();
                } else {
                  that.$message.error("删除失败，请稍后重试！");
                }
                resolve();
              })
              .catch((_) => {})
              .finally((_) => {});
          }).catch(() => console.log("Oops errors!"));
        },
      });
    },

    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.handleSearch();
    },

    //监听树形选择
    onSelect(selectedKeys, info) {
      this.currentTreeNode = info.node.dataRef;
      this.selectedKeys = selectedKeys;
      this.pager.page = 1;
      this.pager.pageSize = 20;
      this.handleSearch();
    },

    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },

    //过滤树形数据
    filterTree(data, children = "children", filterFunc) {
      return data
        .filter((node) => {
          // 如果当前节点符合条件，直接返回true
          if (filterFunc(node)) {
            return true;
          }
          // 如果当前节点有子节点，递归过滤子节点
          if (node[children]) {
            node[children] = this.filterTree(
              node[children],
              children,
              filterFunc
            );
            // 如果过滤后的子节点不为空，说明当前节点需要保留
            return node[children].length > 0;
          }
          // 当前节点不符合条件，也没有子节点或子节点不符合条件，返回false
          return false;
        })
        .map((node) => {
          // 创建新对象，避免修改原始数据
          return {
            ...node,
            [children]: node[children]
              ? this.filterTree(node[children], children, filterFunc)
              : [],
          };
        });
    },

    moment,
  },
};
</script>
<style lang="less" scoped>
.drawing-manage-container {
  display: flex;
  flex-direction: column;
  position: relative;
  .search-condition-warp {
    background: #fff;
    margin-bottom: 10px;
    padding: 10px 16px;
    border-radius: 6px;
    flex-shrink: 0;
    display: flex;
    .condition-warp {
      margin-right: 10px;
      .ant-select {
        margin-right: 10px;
      }
      .ant-input {
        margin-left: 10px;
      }
      .ant-calendar-picker {
        margin-left: 10px;
      }
    }
    .button-warp {
      button {
        &:not(:last-child) {
          margin-right: 10px;
        }
      }
    }
  }
  .result-body-warp {
    flex: 1;
    display: flex;
    overflow: hidden;
    .drawing-container {
      height: 100%;
      width: 300px;
      background: #fff;
      margin-right: 10px;
      border-radius: 6px;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      .header {
        flex-shrink: 0;
        height: 56px;
        border-bottom: 1px solid #d9d9d9;
        display: flex;
        align-items: center;
        padding: 0 16px;
        align-items: center;
        justify-content: space-between;
        color: #333333;
        font-size: 16px;
        .add-file-button {
          color: #8c8c8c;
          font-size: 18px;
        }
      }
      .condition {
        flex-shrink: 0;
        padding: 16px 0 10px 0;
        display: flex;
        justify-content: center;
        position: relative;

        input {
          width: 268px;
          padding-right: 36px;
        }
        .search-btn {
          position: absolute;
          width: 30px;
          height: 28px;
          background: #fff;
          top: 18px;
          right: 18px;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          color: #8c8c8c;
          font-size: 20px;
        }
      }
      .tree-container {
        flex: 1;
        overflow: auto;
        overflow-x: hidden;
        position: relative;
        padding: 0 10px 0 14px;
        /deep/.ant-tree {
          .ant-tree-node-content-wrapper {
            &:hover {
              .operate {
                .anticon {
                  display: inline-block !important;
                }
              }
            }
          }
          li {
            width: 100%;
            .ant-tree-switcher {
              width: 18px;
            }
            .ant-tree-node-content-wrapper {
              position: relative;
              width: calc(100% - 25px);
              padding: 0;
              .ant-tree-iconEle {
                color: #f3ab1f;
                font-size: 16px;
              }
              .ant-tree-title {
                overflow: hidden;
                display: inline-block;
                width: calc(100% - 26px);
                .custom-tree-title-warp {
                  display: flex;
                  width: 100%;
                  .title {
                    flex: 1;
                    overflow: hidden;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                  }
                  .operate {
                    flex-shrink: 0;
                    margin-left: 8px;
                    color: #8c8c8c;
                    width: 59px;
                    .anticon {
                      display: none;
                    }
                    .add-file-button {
                      font-size: 15px;
                    }
                    .edit-btn {
                      margin: 0 8px;
                    }
                  }
                }
              }
            }
          }
        }
        .ant-empty {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
        }
      }
    }
    .right-container {
      height: 100%;
      flex: 1;
      background: #fff;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      .header {
        height: 60px;
        flex-shrink: 0;
        display: flex;
        align-items: center;
        padding: 0 16px;
        button {
          &[disabled] {
            background-color: #f5f5f5 !important;
          }
        }
      }
      .table-container {
        flex: 1;
        overflow: hidden;
        padding: 0 16px;
        .preview-btn {
          color: #1677ff;
          margin-right: 16px;
          font-size: 15px;
        }
        .download-btn {
          color: #239b53;
          font-size: 16px;
        }
        .edit-btn {
          color: #239b53;
          margin-right: 16px;
          font-size: 15px;
        }
        .delete-btn {
          color: #e43d3d;
          font-size: 15px;
        }

        .correlation-model {
          color: #1677ff;
          font-size: 14px;
          .anticon {
            color: #239b53;
            margin-right: 6px;
          }
          &.no {
            .anticon {
              color: #ff2d2d;
            }
          }
          &.no {
            .anticon {
              color: #ff2d2d;
            }
          }
        }
      }
      .pager-container {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        flex-shrink: 0;
        height: 100px;
        padding-right: 10px;
      }
    }
  }
}
</style>
